import cgi
import json
import os
import urllib

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template

class Suggestion(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

class SuggestPage(webapp.RequestHandler):
    def get(self):
        suggestions = db.GqlQuery("SELECT * FROM Suggestion ORDER BY author  DESC LIMIT 10")

        author_dict = {}
        for item in suggestions:
            author_dict.setdefault(item.author, []).append(item)
            
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'author_dict': author_dict,
            'suggestions': suggestions,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'suggestions.html')

        self.response.out.write(template.render(path, template_values))
        
    def GetAuthors(self):
        return '1@example.com'

class MainPage(webapp.RequestHandler):
    def get(self):
        suggestion_query = Suggestion.all().order('-date')
        suggestions = suggestion_query.fetch(10)

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        template_values = {
            'suggestions': suggestions,
            'url': url,
            'url_linktext': url_linktext,
        }

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

class GuestBook(webapp.RequestHandler):
    def post(self):
        suggestion = Suggestion()
        if users.get_current_user():
            suggestion.author = users.get_current_user()
        suggestion.content = self.request.get('content')
        suggestion.put()
        self.redirect('/')

class LoginPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        path = os.path.join(os.path.dirname(__file__), 'login.html')
        self.response.out.write(template.render(path, template_values))

class Start(webapp.RequestHandler):
    def get(self):
        code = self.request.get('code')
        appId = "224792924213256"
        appSecret = "cb64a4fe09c0e98822778ef10b66c8ed"
        redirecturl = "http://localhost:8080/start"
        stupidAuthRequest = ("https://graph.facebook.com/oauth/access_token?"
                             "client_id=%s&redirect_uri=%s&"
                             "client_secret=%s&code=%s") % (appId, redirecturl, appSecret, code)

        filehandle = urllib.urlopen(stupidAuthRequest)
        stuff = filehandle.read()
        authToken = stuff.split('&')[0].split('=')[1]
        expires = stuff.split('&')[1].split('=')[1]

        graphUrl = "https://graph.facebook.com/me?access_token=" + authToken
        me = urllib.urlopen(graphUrl).read()
	me_json = json.loads(me)

        graphUrl = "https://graph.facebook.com/me/friends?access_token=" + authToken
        friends = urllib.urlopen(graphUrl).read()
	friends_json = json.loads(friends)

        moviesUrl = "https://graph.facebook.com/707196162/movies?access_token=" + authToken
        movies = urllib.urlopen(moviesUrl).read()
	movies_json = json.loads(movies)
        movie_name = movies_json['data'][0]['name']


        template_values = {'code' : code,
                           'stuff': stuff,
                           'graphUrl' : graphUrl,
                           'name': me_json['name'],
                           'id' : me_json['id'],
			   'friends_json': friends_json,
                           'movie_name': movie_name}
        path = os.path.join(os.path.dirname(__file__), 'start.html')
        self.response.out.write(template.render(path, template_values))

        
        
application = webapp.WSGIApplication(
    [('/', MainPage),
     ('/submit', GuestBook),
     ('/suggest', SuggestPage),
     ('/login', LoginPage),
     ('/start', Start)],
    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()        
